//
//  EnterpriseViewController.swift
//  BusinessIOS
//
//  Created by Rain on 2018/11/9.
//  Copyright © 2018 XingJian Li. All rights reserved.
//

import UIKit
import Alamofire
class EnterpriseViewController: UIViewController {
    var tableView: UITableView!
    var EnterpriseArray = [EnterpriseModel]()
    
    
    var bigEnterpriseArray = [EnterpriseModel]()
    
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var index = 1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = bgGrayColor;
        navigationItem.title="企业信息库"
        tableView = UITableView(frame:self.view.frame, style:.grouped)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        

        tableView.tableFooterView = UIView.init()
        
        
        tableView.register(NSClassFromString("ContentTableViewCell"), forCellReuseIdentifier: "ContentCell")
        
//        tableView.register(NSClassFromString("EnterpriseTableViewCell"), forCellReuseIdentifier: "EnterpriseTableViewCell")
        tableView.register(NSClassFromString("ButtTableViewCell"), forCellReuseIdentifier: "ButtTableViewCell")
        
        tableView.register(NSClassFromString("BusinessdetailsTableViewCell"), forCellReuseIdentifier: "BusinessdetailsTableViewCell")
        
        
        
        
        
        view.addSubview(tableView)
        tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
        
        
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        // 现在的版本要用mj_header
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
        
        
//
//         self.loadData()
    }
    // 顶部刷新
    @objc func headerRefresh(){
        self.EnterpriseArray.removeAll()
        self.bigEnterpriseArray.removeAll()
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/companyinformation/getList"
        
        let json = "{\"start\":\"\(1)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            print("========\(response)")
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   EnterpriseModel()
                    
                    
                    
                    model1.foreignInvestment = dataDic["foreignInvestment"].string
                    
                    model1.id = dataDic["id"].string
                    
                    
                    
                    
                    
                    self.EnterpriseArray.append(model1)
                    
                    
                    print("DynamicArray====\(self.EnterpriseArray.count)")
                    
                }
                
      
                self.bigEnterpriseArray.append(contentsOf: self.EnterpriseArray)
                
                self.tableView.reloadData()
                
                self.tableView.mj_header.endRefreshing()
                
            }else{
                self.tableView.mj_header.endRefreshing()
            }
            
        }
        
    }
    

    @objc func footerRefresh(){
        self.EnterpriseArray.removeAll()
        
        index += 1
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/companyinformation/getList"
        
        let json = "{\"start\":\"\(index)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            print("========\(response)")
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   EnterpriseModel()
                    
                    
                    
                    model1.foreignInvestment = dataDic["foreignInvestment"].string
                    
                    model1.id = dataDic["id"].string
                    
                    
                    
                    
                    
                    self.EnterpriseArray.append(model1)
                    
                    
                    print("DynamicArray====\(self.EnterpriseArray.count)")
                    
                }
                
                
                self.bigEnterpriseArray.append(contentsOf: self.EnterpriseArray)
                
                self.tableView.reloadData()
                
                self.tableView.mj_footer.endRefreshing()
                
            }else{
                self.tableView.mj_footer.endRefreshing()
            }
            
        }
        
        
    }
    func loadData(){
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/companyinformation/getList"
        
        let json = "{\"start\":\"\(1)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            print("========\(response)")
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   EnterpriseModel()
                    
      
                    
                    model1.foreignInvestment = dataDic["foreignInvestment"].string
                    
                    model1.id = dataDic["id"].string
                    

                    
                    
                    
                    self.EnterpriseArray.append(model1)
                    
                    
                    print("DynamicArray====\(self.EnterpriseArray.count)")
                    
                }
                
                self.tableView.reloadData()
                
                
            }else{
                
            }
            
        }
            
            
            
        }



}

extension EnterpriseViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.bigEnterpriseArray.count

    }

//    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//        if section == 0{
//            return ""
//        }else{
//            return "我的待办"
//        }
//        
//    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      
        return 40
        
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    
    
    
    //返回分区头部视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
//
//        if section == 0 {
//            return nil
//        }else{
            let headerView = UIView()
            headerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 40)
            headerView.backgroundColor = UIColor.white
            let titleLabel = UILabel()
            titleLabel.text = "企业编号"
            titleLabel.textAlignment = .center
            titleLabel.textColor = UIColor.black
            titleLabel.font = UIFont.systemFont(ofSize:14)//一般方法
            titleLabel.sizeToFit()
            
            headerView.addSubview(titleLabel)
            
            
            let headerButton = UILabel()
            headerButton.font = UIFont.systemFont(ofSize:14)//一般方法
            headerButton.text = "企业名称"
            headerButton.textAlignment = .center
            headerButton.textColor = UIColor.black
           
            headerButton.sizeToFit()
            
            
            headerView.addSubview(headerButton)
            
            
            
            titleLabel.snp.makeConstraints { (make) in
                make.top.equalTo(headerView.snp.top).offset(5)
                make.left.equalTo(headerView.snp.left).offset(10)
                make.width.equalTo(100)
                make.height.equalTo(30)
            }
            
            
            headerButton.snp.makeConstraints { (make) in
                make.top.equalTo(headerView.snp.top).offset(5)
                make.left.equalTo(titleLabel.snp.right).offset(10)
                make.right.equalTo(headerView.snp.right).offset(-10)
                make.height.equalTo(30)
            }
            
            
            
            
            return headerView
//        }
        
    }
    //返回分区头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
     
        return 40
    
      
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
         let cellModel:EnterpriseModel = self.bigEnterpriseArray[indexPath.row]
            
        let cell = BusinessdetailsTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "BusinessdetailsTableViewCell")
        cell.selectionStyle = .none
        
        
        cell.BusinessdetailsTableViewCell(model: cellModel)
            return cell
   
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        let cellModel:EnterpriseModel = self.bigEnterpriseArray[indexPath.row]
        
        //实例化一个将要跳转的viewController
        let DetailsVc = DetailsViewController()
        DetailsVc.numberString = cellModel.id
        self.navigationController?.pushViewController(DetailsVc , animated: true)
    }
    
}
